%%% File    : router.erl
%%% Author  :  <>
%%% Description : 
%%% Created : 26 Mar 2011 by  <>

-module(router).

-export([router/1]).


%%------
router(Msg) when is_list(Msg) ->
    router(list_to_binary(Msg), 3).

router(Bin, 0) ->
    io:format("deliver msg ~p failed~n", [binary_to_list(Bin)]),
    ok;
router(Bin = <<_Type:8, Toid:4/binary, _Fromid:4/binary, _Msg/binary>>, Try) ->
    case catch gen_server:call({global, cache_server}, {request, Toid}) of
	{'EXIT', _Pid} ->
	    sleep(500),
	    router(Bin, Try-1);
	{ok, Pid} ->
	    wait(Pid, binary_to_list(Bin));
	_Others ->
	    sleep(500),
	    router(Bin, Try-1)
     end.

wait(Pid, List) ->
    case catch gen_server:call(Pid, {msg, List}) of
	{'EXIT', Pid} ->
	    sleep(500),
	    router(list_to_binary(List), 3);
	ok ->  %%%send the ack
	    ok;
	_Others ->
	    ok
    end.
sleep(T) ->
    receive
    after T ->
	    ok
    end.
